package com.evision.webcrawler.configure;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ProcessorRedisManager {
    private Logger logger = LoggerFactory.getLogger(ProcessorRedisManager.class);

    private static final String PNAME = "PNAME";
    private static final String PNAME_CLASS_MAP = "PM_CLASS_MAP";
    private List<String> processNameList = null;
    private Map<String, String> processClassMap = new HashMap<>();
    private RedisTemplate template;

    public ProcessorRedisManager(RedisTemplate template) {
        this.template = template;
        init();
    }

    public List<String> getProcessNameList() {
        return processNameList;
    }

    public void setProcessNameList(List<String> processNameList) {
        this.processNameList = processNameList;
    }

    public Map<String, String> getProcessClassMap() {
        return processClassMap;
    }

    public void setProcessClassMap(Map<String, String> processClassMap) {
        this.processClassMap = processClassMap;
    }

    public void init() {
        processClassMap.clear();
        long size = template.opsForList().size(PNAME);
        processNameList = template.opsForList().range(PNAME, 0, size);
        List<String> pclass = template.opsForHash().multiGet(PNAME_CLASS_MAP, processNameList);
        for (int i = 0; i < processNameList.size(); i++) {
            processClassMap.put(processNameList.get(i), pclass.get(i));
            logger.info("PROCESS KEY:["+processNameList.get(i)+"],CLASS:["+pclass.get(i)+"]");
        }
    }

    public void addProcessor(String pname, String className) {
        template.opsForList().rightPush(ProcessorRedisManager.PNAME, pname);
        template.opsForHash().put(ProcessorRedisManager.PNAME_CLASS_MAP,pname,className);
    }

}
